import pandas as pd
import numpy as np
import mysql.connector
import pymongo
import logging
import os
import datetime

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('logs/ranking_layer.log'),
        logging.StreamHandler()
    ]
)

class RankingLayer:
    def __init__(self):
        # 创建日志目录
        os.makedirs('logs', exist_ok=True)
        
        # 获取日志记录器
        self.logger = logging.getLogger(__name__)
        
        # 连接MySQL
        try:
            self.mysql_conn = mysql.connector.connect(
                host="localhost",
                user="root",
                password="123",
                database="user"
            )
            self.logger.info("MySQL连接成功")
        except Exception as e:
            self.logger.error(f"MySQL连接失败: {e}")
            raise
        
        # 连接MongoDB
        try:
            self.mongo_client = pymongo.MongoClient("mongodb://localhost:27017/")
            self.db = self.mongo_client["farmer"]
            self.collection = self.db["孜然"]
            self.logger.info("MongoDB连接成功")
        except Exception as e:
            self.logger.error(f"MongoDB连接失败: {e}")
            raise
    
    def rank_candidates(self, candidates, user_id):
        self.logger.info(f"开始对用户 {user_id} 的候选商品进行排序")
        try:
            ranked = []
            for product_id in candidates:
                product = self.collection.find_one({"_id": product_id})
                if not product:
                    self.logger.warning(f"商品 {product_id} 未找到")
                    continue
                
                # 计算推荐权重
                interest_match = 1.0  # 简化为固定值
                discount_factor = (product["original_price"] - product["current_price"]) / product["original_price"]
                time_decay = np.exp(-0.1 * (datetime.datetime.now() - datetime.datetime.strptime(product["listed_date"], "%Y-%m-%d")).days)
                
                weight = interest_match * (1 + discount_factor) * time_decay
                
                # 查询用户历史客单价
                query = f"SELECT AVG(total_amount) as avg_order_value FROM buy WHERE user_id = {user_id}"
                avg_order_value = pd.read_sql(query, self.mysql_conn).iloc[0]["avg_order_value"]
                
                # 对价格敏感用户增加权重
                if avg_order_value < 50:
                    weight *= 1.3
                
                ranked.append((product_id, weight))
            
            # 按权重排序
            ranked.sort(key=lambda x: x[1], reverse=True)
            self.logger.info(f"排序完成，排序后商品数量: {len(ranked)}")
            
            return ranked
        except Exception as e:
            self.logger.error(f"排序失败: {e}")
            return []